from urllib.parse import urlparse, parse_qs

import requests

from config.config import get_upload_dir_path
from service.ResDataService import get_end_data
from service.StatusEnum import StatusEnum
from tools.Func import wait_for_file_content
from tools.Result import success_result


def get_params(url):
    parsed_url = urlparse(url)
    query_params = parse_qs(parsed_url.query)
    auction_codes = query_params.get('auctionCode', [])
    bid_codes=query_params.get('bidCode', [])
    auction_code= auction_codes[0] if auction_codes else None
    bid_code= bid_codes[0] if bid_codes else None
    return auction_code, bid_code


def get_djjx_post_request(url):
    post_url = "https://www.dajiajixie.com/awi/data/getBidCorpVoByCode"
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Connection": "keep-alive",
        "Content-Type": "application/json;charset=UTF-8",
        "User-Agent": "PostmanRuntime-ApipostRuntime/1.1.0"
    }
    cookie=wait_for_file_content(get_upload_dir_path()+"djjx_cookie")
    cookies = {
        "ufastSession": cookie
    }
    auction_code, bid_code = get_params(url)
    # 请求 JSON 数据体
    payload = {
        "auctionCode": auction_code,
        "corporeCode": bid_code
    }
    try:
        response = requests.post(
            post_url,
            json=payload,  # 自动处理 JSON 序列化
            headers=headers,
            cookies=cookies,
            timeout=15
        )
        response.raise_for_status()  # 检查 HTTP 错误状态码



        return get_result(response.json())

    except requests.exceptions.RequestException as e:
        print(f"请求异常: {e}")
        return None

def get_result(result):
    start_price=result.get("data", {}).get("startPrice", "")
    current_price=result.get("data", {}).get("currPrice", "")
    auction_status = result.get("data", {}).get("auctionStatus", 0)
    corpore_status=result.get("data", {}).get("corporeStatus", 0)
    print(result.get("data", {}))
    return success_result("成功",get_end_data(start_price, current_price,get_status(auction_status,corpore_status)))

def get_status(auction_status,corpore_status):
    status = auction_status+1
    if auction_status==2 and corpore_status==1:
        status=5
    if auction_status==2 and corpore_status==2:
        status=4
    return StatusEnum.get_common_info(status)
